package com.aivin.waterfallflow.callback;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;


public abstract class StaggeredGridLayoutManagerEndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {

    private boolean isSlidingUpward = false;
    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);

        StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
        if(manager==null){
            throw new RuntimeException("manager is null ....") ;
        }

        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            int []  positions = manager.findLastVisibleItemPositions(null);
            int lastPos=0 ;
            for(int pos : positions){
                if(pos > lastPos){
                    lastPos = pos;
                }
            }
            int itemCount = manager.getItemCount();

            if (lastPos == (itemCount - 1) && isSlidingUpward) {
                onLoadMore();
            }
        }
    }
    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        isSlidingUpward = dy > 0;
    }

    public abstract void onLoadMore();
}
